package com.gexin.model.weixin;

import com.gexin.common.cache.CacheUtils;
import com.gexin.common.cache.RedisKeyConst;
import com.gexin.common.utils.DateUtil;
import com.gexin.common.utils.SQLUtils;
import com.gexin.common.utils.StringUtil;
import com.gexin.model.weixin.base.BaseWeixinUser;
import com.gexin.weixin.kit.EmojiUtils;
import com.gexin.weixin.kit.WeiXinRedisKey;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.weixin.sdk.api.ApiResult;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 业务名称:  t_weixin_user(微信用户表) 
 */
@SuppressWarnings("serial")
public class WeixinUser extends BaseWeixinUser<WeixinUser> {
    public static final WeixinUser dao = new WeixinUser();
    /**取消关注**/
    public static final int Subscribe_Cancel=0;
    /**已经关注**/
    public static final int Subscribe_In=1;
	public static final String cache_User_TokenGetUserfd = "cache:user:token:";
	public static final String cache_user_loginToken = "cache:user:logonToken:";
    /**
     * 更新用户的关注和取消状态
     * @param openId  用户的openid
     * @param state  0取消关注 1新增关注
     */
    public void update_follow(String openid,int state){
        String key = WeiXinRedisKey.getWeiXinUserByOpenid+openid;//缓存
        CacheUtils.del(key);
        Db.update("update t_weixin_user set subscribe=? ,un_subscribe_time=? where openid=?",state,new Date(),openid);//设置取消关注
    }


	/**
	 * 从缓存里面读取用户的推送的ID
	 * @param id 用户的ID
	 * @return 如果返回 null 表示没有就不推送消息
	 */
	public String cache_getJpulishId(Integer id) {
		if (id == null) {
			return null;
		}
		String key = RedisKeyConst.User_JPulishId + id;
		String jpushId = CacheUtils.get(key);
		if (jpushId == null) {
			jpushId = dao.findByIdLoadColumns(id, "id,jpushid").getStr("jpushid");
			if (null != jpushId) {
				CacheUtils.set(key, jpushId, RedisKeyConst.day);
			}
		}
		return jpushId;
	}

	/**
	 * 根据绑定手机查询
	 * @param phone
	 * @return
	 */
	public WeixinUser findbyBindPhone(String phone){
		return dao.findFirst(" select * from t_weixin_user where bind_phone=? ",phone);
	}

	/**
	 * 更新用户的推送的ID
	 * @param id
	 * @param jpushid
	 */
	public void cache_setJpulishId(Integer id, String jpushid) {
		String key = RedisKeyConst.User_JPulishId + id;
		if (StringUtil.isNotBlank(jpushid)) {
			if (dao.findByIdLoadColumns(id, "id,jpushid").set("jpushid", jpushid).update()) {
				CacheUtils.set(key, jpushid, RedisKeyConst.day);
			}
		}
	}

	/**
	 * 检验Token 是否有效
	 * @param token
	 * @return
	 */
	public Integer isActiveToken(String token) {
		Integer cache_userid = CacheUtils.get(cache_User_TokenGetUserfd + token);
		return cache_userid;
	}

	/**
	 * 检验Token 是否有效
	 * @param token
	 * @param userid 用户id
	 * @return
	 */
	public boolean isActiveToken(String token, Integer userid) {
		String cache_userid = CacheUtils.get(cache_User_TokenGetUserfd + token);
		if (userid.equals(cache_userid)) {
			return true;
		}
		WeixinUser user = findByIdLoadColumns(userid, "login_token");
		if (user != null && token.equals(user.getWxToken())) {
			CacheUtils.set(cache_User_TokenGetUserfd + token, userid);
			return true;
		}
		return false;
	}


	//查询微信用户 分页
    public Page<WeixinUser> paginate(int pageNumber, int pageSize, WeixinUser user, String appConfigId) {
        SQLUtils sql  = new SQLUtils(" from t_weixin_user  where 1=1 ");
        if (user!=null) {

            if (StringUtil.isEmpty(user.getNickname())==false) {
                sql.whereLike("nickname", user.getNickname());
            }

            if (user.getSex()!=null) {
                sql.whereEquals("sex", user.getSex());
            }
        }
        if (StringUtil.isEmpty(appConfigId)==false) {
            sql.whereEquals("appid", appConfigId);
        }
        sql.append(" order by subscribe_time desc");
        return paginate(pageNumber, pageSize, "select * ", sql.toString());
    }

    /**
     * 根据用户的openid  查询用户的信息
     * @param openid  用户的openid
     * @return  用户的实体
     */
    public WeixinUser getUserByOpentId(String openid){
        return findFirst("select * from  t_weixin_user where openid =? ",openid);
    }

	public WeixinUser getUserByUnionid(String unionid){
		return findFirst("select * from  t_weixin_user  where unionid =? ",unionid);
	}


    public WeixinUser getUserById(Integer id){
        return findById(id);
    }

    /**
     * 从缓存里面读取  用户信息  根据用户的openid
     * @param openid
     * @return
     */
    public WeixinUser cache_getUserByOpentId(String openid){
        String  key  = WeiXinRedisKey.getWeiXinUserByOpenid+openid;
        WeixinUser user  =  CacheUtils.get(key);
        if(user==null){
            user=  getUserByOpentId(openid);
            if(user!=null){
                CacheUtils.set(key,user,WeiXinRedisKey.getWeiXinUserByOpenid_time);
            }
        }
        return  user;
    }

    /**
     * 根据用户的ID  获取openid
     * @param uid  用户的Id
     * @return
     */
    public String  cache_getUserOpenid(Integer  uid){
        String  key  = WeiXinRedisKey.getWeiXinUserOpenid+uid;
        String data  =  CacheUtils.get(key);
        if(StringUtil.isNotBlank(data)){
            return data;
        }
        WeixinUser user  =findByIdLoadColumns(uid, "id,openid");
        if(user!=null){
            data  =user.getOpenid();
            CacheUtils.set(key,data,RedisKeyConst.day*20);//缓存二十天
        }
        return  data;
    }
    /**
     * 从缓存里面读取  用户信息  根据用户的id
     * @param id
     * @return
     */
    public WeixinUser cache_getUserById(Integer id){
        String  key  = WeiXinRedisKey.getWeiXinUserByOpenid+id;
        WeixinUser user  =  CacheUtils.get(key);
        if(user==null){
            user=  getUserById(id);
            if(user!=null){
                CacheUtils.set(key,user,WeiXinRedisKey.getWeiXinUserByOpenid_time);
            }
        }
        return  user;
    }

    //清除缓存
    public void cache_ClearByUserId(Integer  uid){
        CacheUtils.del(WeiXinRedisKey.getWeiXinUserByOpenid+uid);
        CacheUtils.del(WeiXinRedisKey.getWeiXinUserByOpenid+cache_getUserOpenid(uid));
    }

    @Override
    public boolean save(){
        if(getId()==null){
            return super.save();
        }else{
            cache_ClearByUserId(getId());
            return super.update();
        }
    }

    @Override
    public boolean update(){
        cache_ClearByUserId(getId());
        return super.update();
    }

    /**
     * 把微信请求过来的对象转换成
     * @param result
     * @return
     */
    public WeixinUser paseWxUser(ApiResult  result){
        WeixinUser user  =findFirst("select * from t_weixin_user where  openid=?",result.getStr("openid"));
        if(user==null){
            user=new WeixinUser();
        }
        user.setOpenid(result.getStr("openid"));
        user.setSubscribe(result.getInt("subscribe"));
        user.setNickname(EmojiUtils.emojiChange(result.getStr("nickname")));
        user.setSex(result.getInt("sex"));
        user.setLanguage(result.getStr("language"));
        user.setCity(result.getStr("city"));
        user.setProvince(result.getStr("province"));
        user.setCountry(result.getStr("country"));
        user.setHeadimgurl(result.getStr("headimgurl"));
        if(result.get("subscribe_time")!=null){
            user.setSubscribeTime(DateUtil.getTimestampToDate(result.get("subscribe_time").toString()));
        }
        user.setRemark(result.getStr("remark"));
        try {
            user.setGroupid(result.getStr("groupid"));
        } catch (Exception e) {
            user.setGroupid(String.valueOf(result.getInt("groupid")));
        }

        user.setUnionid(result.getStr("unionid"));
        return user;
    }

    public static String filterEmoji(String source) {
        return EmojiUtils.emojiChange(source);
    }

    /**
     * 根据关注类型查询粉丝信息 分页
     * @param pageNumber
     * @param pageSize
     * @param user
     * @return
     */
    public Page<WeixinUser> fansPaginate(int pageNumber, int pageSize, WeixinUser user) {
        List<Object> parameters=new LinkedList<Object>();
        SQLUtils sql = new SQLUtils(" from t_fans_concern c left join t_weixin_user u on u.id=c.user_id  ");
        if (user.getInt("fans_type")==1){
            sql.append(" where c.celebrity_id=? and c.type=? ");
        }else {
            sql.append(" where c.fans_club_id=? and c.type=? ");
        }
        System.err.println(user.getInt("fans_relevance_id"));
        System.err.println(user.getInt("fans_type"));
        parameters.add(user.getInt("fans_relevance_id"));
        parameters.add(user.getInt("fans_type"));
        if (StringUtil.isNotBlank(user.getNickname())){
            sql.append(" and u.nickname like ? ");
            parameters.add("%"+user.getNickname()+"%");
        }
        if (user.getSex()!=null){
            sql.append(" and u.sex=? ");
            parameters.add(user.getSex());
        }
        sql.append(" group by u.id  ");
        return paginate(pageNumber,pageSize," select u.*,c.create_time concern_time  ",sql.toString(),parameters.toArray());
    }

    public WeixinUser findByPhoneNumber(String phone) {

        return findFirst("select * from t_weixin_user where username=? or mobile=? or bind_phone=?",phone,phone,phone);
    }

    public WeixinUser findByUserId(String userId) {
        return findFirst("select nickname from t_weixin_user where user_id=?",userId);
    }

	public Page<WeixinUser> findByExtensionId(int page , int pageSize , String agentId) {
		SQLUtils sql = new SQLUtils(" from t_weixin_user u  ");
		sql.append(" where u.extension_id=?  ");
		return paginate(page,pageSize," select u.*  ",sql.toString(),agentId);
	}


	/**
	 * 根据unionid查询公众号的用户
	 * @param unionid
	 */
	public WeixinUser findGZHUserByUnionId(String unionid) {
		return findFirst("Select * from t_weixin_user  where unionid=? and appid=1",unionid);
	}

	public WeixinUser getWeixinUser(String id){
        return findFirst("Select * from t_weixin_user  where id=?",id);
    }

    public List<WeixinUser> allWeixinUser(){
        List<WeixinUser> weixinUserList=WeixinUser.dao.find("Select * from t_weixin_user");
        return weixinUserList;
    }
    public WeixinUser oneWeixinUser(String id){
        WeixinUser weixinUser=WeixinUser.dao.findFirst("Select nickname from t_weixin_user where id="+id);
        return weixinUser;
    }

    public WeixinUser onecWeixinUser(String id){
        return findFirst("Select * from t_weixin_user  where mobile=?",id);
    }

}